import {Component, OnInit} from '@angular/core';
import {FormBuilder, FormGroup, Validators} from '@angular/forms';
import {Router} from '@angular/router';
import {ActivatedRoute} from '@angular/router';
import {MessagerService} from 'ng-easyui/components/messager/messager.service';

import {UserService} from '../../service/user.service';
import {Md5} from 'ts-md5';

@Component({
  selector: 'app-modify-password',
  templateUrl: './modify-password.component.html',
  styleUrls: ['./modify-password.component.css']
})
export class ModifyPasswordComponent implements OnInit {
  msg;
  email; // 修改密码唯凭证
  // 表单
  itemForForm: FormGroup = null; // 表单对象
  formBtnDisabled = false; // 默认激活表单提交,true禁用表单提交
  formValidSuccess = true; // 默认成功样式
  placeholder = {
    password: {'title': '新密码', 'prompt': '字母开头,长度在6~10之间,只能包含字母、数字和下划线'},
    rePassword: {'title': '重复新密码', 'prompt': '字母开头,长度在6~10之间,只能包含字母、数字和下划线'},
  };

  /**
   * 构造函数
   */
  constructor(
    private router: Router,
    private activatedRoute: ActivatedRoute,
    private userService: UserService,
    private formBuilder: FormBuilder,
    private messagerService: MessagerService) {
    this.createItemForForm(); // 创建表单对象
  }

  /**
   * 初始化函数
   */
  ngOnInit() {
    if (sessionStorage.getItem('code')) { // 判断本地sessionStorage中是否存储验证通过的code
      this.email = this.activatedRoute.snapshot.paramMap.get('email');
    } else {
      console.log('fail');
      this.router.navigateByUrl('forgetPassword');
    }
  }

  /**
   * 创建表单对象
   */
  createItemForForm(): void {
    this.itemForForm = this.formBuilder.group({
      password: [null, [
        Validators.required,
        Validators.pattern('^[a-zA-Z]\\w{5,9}$')]
      ],
      rePassword: [null, [
        Validators.required,
        Validators.pattern('^[a-zA-Z]\\w{5,9}$')]
      ],
    });
  }

  /**
   * 表单提交
   * @param itemForForm
   */
  onSubmit(itemForForm): void {
    this.formBtnDisabled = true; // 禁用表单提交
    if (this.itemForForm.value.password === this.itemForForm.value.rePassword) {
      itemForForm.value.email = this.email; // 修改密码凭证
      itemForForm.value.password = Md5.hashStr(itemForForm.value.password); // 密码加密
      itemForForm.value.rePassword = null;
      this.userService.modifyPassword(itemForForm.value).subscribe(responseJson => {
        if (responseJson.code === 0) {
          /*
            操作成功
           */
          setTimeout(() => {
            sessionStorage.removeItem('code');
            this.router.navigateByUrl('/login');
          }, 500);
        } else {
          /*
            操作失败
           */
          this.formBtnDisabled = false; // 开启表单提交
          this.formValidSuccess = false; // 失败样式
          this.msg = responseJson.msg;
        }
      });
    } else {
      this.formBtnDisabled = false; // 开启表单提交
      this.formValidSuccess = false; // 失败样式
      this.msg = '密码不一致!';
    }
  }

}
